<?php
/**
 * Created by PhpStorm.
 * User: WD-QD-PHP-DEV-YU
 * Date: 2017/4/27
 * Time: 14:21
 */
namespace app\models;
use app\models\User;
use yii\base\Model;

class SignupForm extends Model
{

    public $username;
    public $password;
    public $password_repeat;
    public $email;

    public function rules()
    {
        return [
            ['username', 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\app\models\User', 'message' => '用户名已存在'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => '邮箱已存在'],

            [['password','password_repeat'], 'required'],
            ['password', 'string', 'min' => 6],
            ['password_repeat', 'compare','compareAttribute'=>'password'],

        ];
    }

    public function attributeLabels()
    {
        return [
            'username'=>'用户名',
            'password'=>'密码',
            'password_repeat'=>'确认密码',
            'email'=>'邮箱'
        ];
    }

    public function signUp(){
        if(!$this->validate()){
            return null;
        }

        $user = new User();
        $user->username = $this->username;
        $user->setPassword($this->password);
        $user->email = $this->email;
        $user->generateAuthKey();

        return $user->save()?$user:null;
    }
}
